import { Message } from 'element-ui';
export const pageConfig = {
	count: 0,
	pageNo: 1,
	pageSize: 100,
	remotePageSize: 50,
	pageSizes: [50, 100]
};
export const filZero = n => n < 10 ? '0' + n : '' + n;

// 清除左右空格，同时中间连续空格只保留一个
export const clearBlankSpace = (str) => {
	return str.replace(/^\s+|\s+$/g, '').replace(/\s{2,}/g, ' ');
};
// 删除crate/update等冗余字段
export const clearRedundancyKey = function(data, otherKeys = []) {
	const cpData = data ? JSON.parse(JSON.stringify(data)) : {};
	const keys = [
		'version', 'createId', 'createName', 'createTime', 'updateId', 'updateName', 'updateTime', 'creator', 'creatorName', 'updater', 'updaterName', 'version',
		...otherKeys
	];
	if (cpData instanceof Array) {
		cpData.forEach(x => {
			keys.forEach(k => {
				delete x[k];
			});
		});
	} else {
		keys.forEach(k => {
			delete cpData[k];
		});
	}
	return cpData;
};
export const tipsBar = function(_this, type, customClass = 'warning', message) {
	switch (type) {
		case 'permission':
			_this.$message({ title: '提示', type: 'warning', center: true, message: '没有操作权限，请联系管理员!' });
			break;
		case 'save':
			_this.$message({ title: '提示', type: 'success', center: true, message: '操作成功!' });
			break;
		case 'operation':
			_this.$message({ title: '提示', type: 'success', center: true, message: '操作成功!' });
			break;
		case 'delete':
			_this.$message({ title: '提示', type: 'success', center: true, message: '删除成功!' });
			break;
		case 'submit':
			_this.$message({ title: '提示', type: 'success', center: true, message: '提交成功!' });
			break;
		case 'cancelSubmit':
			_this.$message({ title: '提示', type: 'success', center: true, message: '已撤销提交!' });
			break;
		case 'saveAudit':
			_this.$message({ title: '提示', type: 'success', center: true, message: '保存并审核!' });
			break;
		case 'updateAudit':
			_this.$message({ title: '提示', type: 'success', center: true, message: '更新并审核!' });
			break;
		case 'audit':
			_this.$message({ title: '提示', type: 'success', center: true, message: '已审核!' });
			break;
		case 'cancelAudit':
			_this.$message({ title: '提示', type: 'success', center: true, message: '已撤销审核!' });
			break;
		case 'close':
			_this.$message({ title: '提示', type: 'success', center: true, message: '已关闭!' });
			break;
		case 'cancelClose':
			_this.$message({ title: '提示', type: 'success', center: true, message: '撤销关闭!' });
			break;
		case 'validator':
			_this.$message({ title: '提示', type: 'warning', center: true, message: '请填写完整!' });
			break;
		case 'disable':
			_this.$message({ title: '提示', type: 'success', center: true, message: '停用成功' });
			break;
		case 'enable':
			_this.$message({ title: '提示', type: 'success', center: true, message: '启用成功' });
			break;
		case 'checkbox':
			_this.$message({ title: '提示', type: 'warning', center: true, message: '请选择操作对象!' });
			break;
		case 'custom':
			_this.$message({ title: '提示', type: `${customClass}`, center: true, message: message });
			break;
	}
};
export const resetForm = (_this, formName = 'ruleForm') => {
	if (_this.$refs[formName]) {
		_this.$refs[formName].resetFields();
	}
};
/**
 * 根据起、止日期算天数
 * 注：1、传时间格式时，会先截取掉时间
 *    2、包含当天，如：dateDiff(2022-10-01,2022-10-01), 返回: 1, 而不是0
 * @parms dateFrom
 * @parms dateTo
 * */
export const dateDiff = function(dateFrom, dateTo) {
	let days = 0;
	const startD = formatDate(dateFrom);
	const endD = formatDate(dateTo);
	const d1 = Date.parse(startD);
	const d2 = Date.parse(endD);
	if (d2 > d1) {
		const diff = Math.abs(d2 - d1);
		days = Math.ceil(diff / 24 / 60 / 60 / 1000) + 1;
	} else {
		if (d2 === d1) {
			days = 1;
		} else {
			days = 0;
		}
	}
	return days;
};

/**
 * 根据起、止时间算截止天数，精确到时分秒
 * 注：1、传时间格式时
 * 返回：788天17时4分46秒
 * */
export const getDayTimeDiff = function(startTime, endTime) {
	const d1 = new Date(startTime).getTime();
	const d2 = new Date(endTime).getTime();
	const diff = (d2 - d1) / 1000;
	let day = Math.floor(diff / (24 * 60 * 60));
	// 跨天加1
	if (formatDate(endTime) > formatDate(startTime)) {
		day = day + 1;
	}
	const house = Math.floor((diff / (60 * 60)) % 24);
	const minute = Math.floor((diff / 60) % 60);
	const second = Math.floor(diff % 60);
	return `${day}天${house}时${minute}分${second}秒`;
};

/**
 * 根据起、止日期算天数
 * 注：1、传时间格式时
 * 返回：9.5天
 * */
export const getDayDiff = function(startTime, endTime) {
	const d1 = new Date(startTime).getTime();
	const d2 = new Date(endTime).getTime();
	const diff = (d2 - d1) / 1000;
	let day = Math.floor(diff / (24 * 60 * 60));
	// 跨天加1
	if (formatDate(endTime) > formatDate(startTime)) {
		day = day + 1;
	}
	const house = Math.floor((diff / (60 * 60)) % 24) / 24;
	const d = (day + house).toFixed(1);
	return Number(d);
};

// 获取相差小时数
export const getDiffHours = function(startTime, endTime) {
	let hours = 0;
	// 结束时间必须大于开始时间
	if (endTime > startTime) {
		const startSta = new Date(startTime);
		const endSta = new Date(endTime);

		const diffSecond = endSta - startSta;
		hours = Number((diffSecond / 60 / 60 / 1000).toFixed(2));
	} else {
		hours = -1;
	}
	return hours;
};
// 日期格式转换（精确到秒）
export const formatTime = (d, delimiter = '-') => {
	const date = new Date(d);
	// return date.getFullYear() + '-' + filZero((date.getMonth() + 1)) + '-' + filZero(date.getDate()) + ' ' + filZero(date.getHours()) + ':' + filZero(date.getMinutes()) + ':' + filZero(date.getSeconds());
	return `${date.getFullYear()}${delimiter}${filZero((date.getMonth() + 1))}${delimiter}${filZero(date.getDate())}${delimiter === '' ? '' : ' '}${filZero(date.getHours())}${delimiter === '' ? '' : ':'}${filZero(date.getMinutes())}${delimiter === '' ? '' : ':'}${filZero(date.getSeconds())}`;
};
// 日期格式转换（精确到日）
export const formatDate = (d, delimiter = '-') => {
	const date = new Date(d);
	return `${date.getFullYear()}${delimiter}${filZero((date.getMonth() + 1))}${delimiter}${filZero(date.getDate())}`;
};
// 日期格式转换（时分秒）
export const formatHoursMinutesSecond = (d, delimiter = '-') => {
	const date = new Date(d);
	return `${filZero(date.getHours())}${delimiter === '' ? '' : ':'}${filZero(date.getMinutes())}${delimiter === '' ? '' : ':'}${filZero(date.getSeconds())}`;
};
// 日期格式转换（时分）
export const formatHoursMinutes = (d, delimiter = '-') => {
	const date = new Date(d);
	return `${filZero(date.getHours())}${delimiter === '' ? '' : ':'}${filZero(date.getMinutes())}`;
};
// 格式化月和日
export const formatMonthDate = (d, delimiter = '-', isFilZero = true) => {
	const date = new Date(d);
	if (isFilZero) {
		return `${filZero((date.getMonth() + 1))}${delimiter}${filZero(date.getDate())}`;
	} else {
		return `${date.getMonth() + 1}${delimiter}${date.getDate()}`;
	}
};
// 日期格式转换（精确到月）
export const formatMonth = (d, delimiter = '-') => {
	const date = new Date(d);
	return `${date.getFullYear()}${delimiter}${filZero((date.getMonth() + 1))}`;
};

// 获取家族
export const getFamily = (list, target, keyName = 'parentId') => {
  let ids = [];
  let names = [];
  if (list.find(x => x.id === target)) {
    ids.push(target);
    names.push(list.find(x => x.id === target).name);
  }
  if (list.length) {
    getParentId(list, target, keyName, ids, names);
  } else {
    ids = [];
    names = [];
  }
  return {
    ids,
    names
  };
};
function getParentId(list, target, keyName, ids, names) {
  if (list.find(x => x.id === target)) {
    const parentId = list.find(x => x.id === target)[keyName];
    list.forEach(x => {
      if (x.id === parentId) {
        ids.unshift(x.id);
        names.unshift(x.name);
        getParentId(list, x.id, keyName, ids, names);
      }
    });
  }
}

// 多根节点
export const createTree = (list, obj, keyName = 'parentId') => {
	let arr = [];
	if (list.length) {
		const minVal = Math.min(...list.map(x => x.id));
    const rootId = list.find(x => x.id === minVal)[keyName];
    arr = getNode(list, obj, rootId, keyName);
  } else {
		arr = [];
	}
	return arr;
};
// 验证是否是日期格式，如：'2024-04-01'通过, 格式'2024-4-1'检验不通过
export const isValidDate = (str) => {
	// 判断是否为 "YYYY-MM-DD" 格式的日期
	const regEx = /^\d{4}-\d{2}-\d{2}$/;
	if (!str.match(regEx)) { return false; } // 格式不正确

	// 将年月日分割为数组
	const parts = str.split('-');

	// 将字符串转换为年、月、日的整型值
	const year = parseInt(parts[0], 10);
	const month = parseInt(parts[1], 10);
	const day = parseInt(parts[2], 10);

	// 使用 JavaScript 的 Date 对象进行日期合法性验证
	const dateObj = new Date(year, month - 1, day);
	if (dateObj.getMonth() + 1 === month && dateObj.getDate() === day && dateObj.getFullYear() === year) {
		return true; // 日期合法
	} else {
		return false; // 日期不合法
	}
};
function getNode(list, obj, nodeId, keyName) {
	obj.children = [];
	list.forEach(item => {
		if (item[keyName] === nodeId) {
			obj.children.push(item);
		}
	});
	if (obj.children && obj.children.length !== 0) {
		obj.children.forEach(item => {
			getNode(list, item, item.id, keyName);
		});
	} else {
		delete obj.children;
	}
	return obj.children;
}

/**
* 防抖:一定时间范围内连续点击时，只执行最后一次
* */
export const debounce = (fn, timer = 1000) => {
	let isClick = null;
	return function() {
		const _this = this;
		if (isClick) {
			clearTimeout(isClick);
		}
		const arg = arguments;
		isClick = setTimeout(() => {
			// 返回参数和指向
			fn.call(_this, arg, _this);
		}, timer);
	};
};

/**
* 节流: 一定时间范围内连续点击时，只执行第一次点击
 *
 * 使用：throttle((e, _this) => {});
* */
export const throttle = (fn, timer = 1000) => {
	let isClick = false;
	return function() {
		const _this = this;
		const arg = arguments;

		if (!isClick) {
			isClick = true;
			// 返回参数和指向
			fn.call(_this, arg, _this);
			setTimeout(() => {
				isClick = false;
			}, timer);
		}
	};
};

// 验证table内必填项的方法
export const validateTableFormData = (list, keys, valid = true) => {
	/**
	 * @list 验证的数据（必须是对象数组）
	 * @keys 验证的字段（必须是数组）
	 *      1.如果是字符串数组，则值必须存在（注：0、null、undefined除外）才能通过
	 *          如：['settlementTypeId', 'bankAccountId', 'amount']
	 *      2.如果是对象数组，同时zeroIsOk为true时，如果值是0也允许通过
	 *          如：[{ keyName: 'amount', zeroIsOk: true }]
	 * @valid 外部表单验证的结果
	 * */
	let pass = true;
	if (valid) {
		if (Array.isArray(keys) && keys.length) {
			pass = list.length ? list.every(x => {
				return keys.every(k => {
					if (typeof keys[0] === 'string') {
						return x[k];
					} else {
						if (k.zeroIsOk) {
							return x[k.keyName] || x[k.keyName] === 0;
						} else {
							return x[k.keyName];
						}
					}
				});
			}) : false;
		} else {
			pass = false;
		}
		if (!pass) {
			Message({ type: 'warning', center: true, message: '请表格内的选项填写完整!' });
		}
	} else {
		pass = false;
		Message({ type: 'warning', center: true, message: '请填写完整!' });
	}
	return pass;
};

// 首字母小写
export const firstCharacterToLowerCase = (e) => {
	let str1 = e.substring(0, 1);
	str1 = str1.toLowerCase();
	return `${str1}${e.substring(1, e.length)}`;
};
// 首字母大写
export const firstCharacterToUpperCase = (e) => {
	let str1 = e.substring(0, 1);
	str1 = str1.toUpperCase();
	return `${str1}${e.substring(1, e.length)}`;
};

// 去除所有空格(包括中间)和中文并转成大写
export const removeSpacesAndChinese = (str) => {
	let str1 = str;
	str1 = str1.replace(/[ ]/g, '');// 去空格
	str1 = str1.replace(/[\u4e00-\u9fa5]/g, '');// 去除中文
	str1 = str1.toUpperCase();
	return str1;
};
